import { Context, Next } from 'koa'
import _ from 'lodash'

export default async (ctx: Context, next: Next) => {
	ctx.return = (data: any, code = 200) => {
		ctx.body = { code, data, msg: 'OK' }
	}

	ctx.success = (response: any) => {
		if (_.isString(response)) response = { msg: response, type: 'success' }
		ctx.body = Object.assign({ code: 200, msg: 'OK', type: 'success' }, response)
	}
	ctx.warning = (response: any) => {
		if (_.isString(response)) response = { msg: response, type: 'warning' }
		ctx.body = Object.assign({ code: 200, msg: 'OK', type: 'warning' }, response)
	}
	ctx.info = (response: any) => {
		if (_.isString(response)) response = { msg: response, type: 'info' }
		ctx.body = Object.assign({ code: 200, msg: 'OK', type: 'info' }, response)
	}
	ctx.error = (response: any) => {
		if (_.isString(response)) {
			ctx.body = {
				code: 400,
				msg: response,
				type: 'error'
			}
			return
		}
		ctx.body = Object.assign({ code: 400, msg: '客户端错误', type: 'error' }, response)
	}

	await next()
}
